import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

// GET /api/debug-field-metadata?tableName=table_c18
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const tableName = searchParams.get('tableName');
    
    const db = getDeviceParameterDb();
    const deviceParameterDb = db as any;
    
    // 检查 parameter_field_metadata 表是否存在
    const tableExistsStmt = deviceParameterDb.db.prepare(`
      SELECT name FROM sqlite_master WHERE type='table' AND name='parameter_field_metadata'
    `);
    const tableExists = tableExistsStmt.get();
    
    // 获取所有表名
    const tablesStmt = deviceParameterDb.db.prepare(`
      SELECT name FROM sqlite_master WHERE type='table'
    `);
    const allTables = tablesStmt.all();
    
    // 如果有表名参数，检查该表的元数据
    let tableFieldsInfo = null;
    let availableTableNames = [];
    
    if (tableExists) {
      // 获取 parameter_field_metadata 表中所有不同的表名
      const tableNamesStmt = deviceParameterDb.db.prepare(`
        SELECT DISTINCT table_name FROM parameter_field_metadata ORDER BY table_name
      `);
      availableTableNames = tableNamesStmt.all();
      
      if (tableName) {
        // 获取指定表的字段元数据
        const fieldsStmt = deviceParameterDb.db.prepare(`
          SELECT * FROM parameter_field_metadata 
          WHERE table_name = ? 
          ORDER BY field_sequence
        `);
        tableFieldsInfo = fieldsStmt.all(tableName);
      }
    }
    
    // 检查设备类型映射表
    let deviceMappings = [];
    const mappingTableExistsStmt = deviceParameterDb.db.prepare(`
      SELECT name FROM sqlite_master WHERE type='table' AND name='device_type_mappings'
    `);
    const mappingTableExists = mappingTableExistsStmt.get();
    
    if (mappingTableExists) {
      const mappingsStmt = deviceParameterDb.db.prepare(`
        SELECT * FROM device_type_mappings LIMIT 10
      `);
      deviceMappings = mappingsStmt.all();
    }
    
    return NextResponse.json({
      success: true,
      data: {
        requestedTableName: tableName,
        parameterFieldMetadataTableExists: !!tableExists,
        deviceMappingsTableExists: !!mappingTableExists,
        allTables: allTables.map(t => t.name),
        availableTableNames: availableTableNames.map(t => t.table_name),
        tableFieldsInfo,
        deviceMappings: deviceMappings.slice(0, 3), // 只显示前3个映射作为示例
        summary: {
          totalTables: allTables.length,
          totalFieldMetadataTableNames: availableTableNames.length,
          totalDeviceMappings: deviceMappings.length,
          fieldsForRequestedTable: tableFieldsInfo ? tableFieldsInfo.length : 0
        }
      }
    });
    
  } catch (error) {
    console.error('调试字段元数据失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '调试字段元数据失败'
    }, { status: 500 });
  }
}